<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str; // 导入 Str 类
use Illuminate\Validation\Rule;
use Illuminate\View\View;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests; // 确保导入这个 trait

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;

class UsersController extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
   // protected string $name = '';

    public function __construct()
    {
        $this->middleware('auth')->only(['edit','show','update','destroy']);
        $this->middleware('guest')->only(['create']);
    }

    public function index(): View
    {
        $users = User::paginate(10);
        return view('users.index', compact('users'));
    }

    public function create(): View
    {
        return view('users.create');
    }

    public function show(User $user): View
    {
        // $user->load('posts');
        //    $this->authorize('update', $user);
        $posts = $user->posts()->orderBy('created_at','DESC')->paginate(8);
        return view('users.show', compact('user','posts'));
    }

    public function store(Request $request): \Illuminate\Http\RedirectResponse
    {
        $validatedData = $request->validate([
            'name' => ['required', 'min:3', 'max:25', Rule::unique('users')],
            'email' => ['required', 'email', Rule::unique('users')],
            'password' => ['required', 'min:6', 'confirmed'],
        ]);

        $user = User::create([
            'name' => $validatedData['name'],
            'email' => $validatedData['email'],
            'password' => Hash::make($validatedData['password']),
            //'active_token' => Str::random(60),  // 使用 Str::random 生成 token  和在user.php中的boot的作用是一样的
        ]);

        session()->flash('warning', '恭喜您，注册成功!请前往注册邮箱完成激活');
        $this->sendActiveToEmail($user);

        return redirect()->route('login');
    }

    public function edit(User $user): View
    {
        $this->authorize('update', $user);
        return view('users.edit', compact('user'));
    }

    public function destroy(User $user): \Illuminate\Http\RedirectResponse
    {
        $this->authorize('destroy', $user);
        $user->delete();
        session()->flash('success', '删除成功');
        return redirect()->back();
    }

    public function update(Request $request, User $user): \Illuminate\Http\RedirectResponse
    {
        $this->authorize('update', $user);
        $this->validate($request, [
            'name' => ['required', 'min:3', 'max:25', Rule::unique('users')->ignore($user->id)],
            'password' => ['nullable', 'min:6', 'confirmed'],
        ]);

        $data = [];
        $data['name'] = $request->name;
        if ($request->password) {
            $data['password'] = Hash::make($request->password);
        }
        $user->update($data);
        session()->flash('success', '恭喜你，修改个人页面成功！');
        return redirect()->route('users.show', $user);
    }

    protected function sendActiveToEmail($user): void
    {
        $view = 'emails.active';
        $data = compact('user');
        $to = $user->email;
        $subject = '欢迎注册Message Board账号，请确认邮箱并激活';

        $activationUrl = route('account.active', ['token' => $user->active_token]);
        Mail::send($view, array_merge($data, ['activationUrl' => $activationUrl]), function ($message) use ($to, $subject) {
            $message->to($to)->subject($subject);
        });
    }

    public function accountActive($token): \Illuminate\Http\RedirectResponse
    {
        $user = User::where('active_token', $token)->firstOrFail();
        $user->active_token = null;
        $user->is_actived = true;
        $user->save();

        Auth::login($user);
        session()->flash('success', '恭喜您，激活账号成功！');
        return redirect()->route('users.show', [$user]);
    }

    public function getFans(User $user): \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application
    {
        $fans = $user->fans()->paginate(8);
        $title = $user->name.'的粉丝';
        return view('users.fans', compact('fans', 'title'));
    }

    public function getFanings(User $user): \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application
    {
        $fanings = $user->fanings()->paginate(8);
        $title = $user->name.'关注的人';
        return view('users.fanings', compact('fanings', 'title'));
    }

}
